package cn.wolfcode.web.modules.contract.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import cn.wolfcode.web.modules.custlinkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.custlinkman.service.ITbCustLinkmanService;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.orderinfo.entity.TbOrderInfo;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import cn.wolfcode.web.modules.visitinfo.entity.TbVisit;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.wolfcode.web.modules.contract.entity.TbContract;
import cn.wolfcode.web.modules.contract.service.ITbContractService;

import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author dxb
 * @since 2022-10-12
 */
@Controller
@RequestMapping("contract")
public class TbContractController extends BaseController {

    @Autowired
    private ITbContractService entityService;
    @Autowired
    private ITbCustomerService customerService;

    private static final String LogModule = "TbContract";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv)  {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        mv.setViewName("cust/contract/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('cust:contract:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        mv.setViewName("cust/contract/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('cust:contract:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        mv.setViewName("cust/contract/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('cust:contract:list')")
    public ResponseEntity page(LayuiPage layuiPage,String parameterName,String affixSealStatus,String auditStatus,String nullifyStatus) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        page = entityService.lambdaQuery()
                .like(!StringUtils.isEmpty(parameterName),TbContract::getContractName,parameterName)
                .or()
                .like(!StringUtils.isEmpty(parameterName),TbContract::getContractCode,parameterName)
                .eq(!StringUtils.isEmpty(affixSealStatus),TbContract::getAffixSealStatus,affixSealStatus)
                .eq(!StringUtils.isEmpty(auditStatus),TbContract::getAuditStatus,auditStatus)
                .eq(!StringUtils.isEmpty(nullifyStatus),TbContract::getNullifyStatus,nullifyStatus)
                .page(page);

        List<TbContract> records = page.getRecords();
        for (TbContract record:records) {
            String customerName = customerService.getById(record.getCustId()).getCustomerName();
            record.setCustomerName(customerName);
        }

        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('cust:contract:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbContract entity, HttpServletRequest request) {
        entity.setInputTime(LocalDateTime.now());

        SysUser loginUser = (SysUser)request.getSession().getAttribute(LoginForm.LOGIN_USER_KEY);
        entity.setInputUser(loginUser.getUserId());//录入人
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('cust:contract:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbContract entity) {
        entity.setUpdateTime(LocalDateTime.now()); //自动插入时间
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('cust:contract:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @RequestMapping("export")
    @SysLog(value = LogModules.EXPORT, module = LogModule)
    public void export(String parameterName,String affixSealStatus,String auditStatus,String nullifyStatus, HttpServletResponse response) {
        List<TbContract> list = entityService.lambdaQuery()
                .like(!StringUtils.isEmpty(parameterName),TbContract::getContractName,parameterName)
                .or()
                .like(!StringUtils.isEmpty(parameterName),TbContract::getContractCode,parameterName)
                .eq(!StringUtils.isEmpty(affixSealStatus),TbContract::getAffixSealStatus,affixSealStatus)
                .eq(!StringUtils.isEmpty(auditStatus),TbContract::getAuditStatus,auditStatus)
                .eq(!StringUtils.isEmpty(nullifyStatus),TbContract::getNullifyStatus,nullifyStatus).list();

        for (TbContract record:list) {
            String customerName = customerService.getById(record.getCustId()).getCustomerName();
            record.setCustomerName(customerName);
        }

        ExportParams exportParams = new ExportParams();

        //样式、字节码、内容
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TbContract.class, list);
        try {
            PoiExportHelper.exportExcel(response, "客户合同管理", workbook);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}
